@echo off
chcp 65001 >nul
echo ========================================
echo 寻找Python并初始化数据库
echo ========================================
echo.

REM 尝试各种可能的Python位置
set PYTHON_CMD=

REM 方法1: py启动器
py --version >nul 2>&1
if %errorlevel%==0 (
    set PYTHON_CMD=py
    echo [找到] 使用 py 启动器
    goto :found
)

REM 方法2: python命令
python --version >nul 2>&1
if %errorlevel%==0 (
    set PYTHON_CMD=python
    echo [找到] 使用 python 命令
    goto :found
)

REM 方法3: 常见安装位置
for %%P in (
    "C:\Python311\python.exe"
    "C:\Python310\python.exe"
    "C:\Python39\python.exe"
    "C:\Program Files\Python311\python.exe"
    "C:\Program Files\Python310\python.exe"
    "%LOCALAPPDATA%\Programs\Python\Python311\python.exe"
    "%LOCALAPPDATA%\Programs\Python\Python310\python.exe"
) do (
    if exist %%P (
        set PYTHON_CMD=%%P
        echo [找到] Python位置: %%P
        goto :found
    )
)

echo.
echo [错误] 未找到Python安装
echo.
echo 请先安装Python:
echo 1. 访问 https://www.python.org/downloads/
echo 2. 下载并安装Python 3.9或更高版本
echo 3. 安装时务必勾选 "Add Python to PATH"
echo.
pause
exit /b 1

:found
echo.
echo ----------------------------------------
echo [1] 检查Python版本
echo ----------------------------------------
%PYTHON_CMD% --version
echo.

echo ----------------------------------------
echo [2] 检查Django
echo ----------------------------------------
%PYTHON_CMD% -c "import django; print('Django版本:', django.get_version())" 2>nul
if %errorlevel% neq 0 (
    echo Django未安装，正在安装...
    %PYTHON_CMD% -m pip install django djangorestframework django-cors-headers
)
echo.

echo ----------------------------------------
echo [3] 执行数据库迁移
echo ----------------------------------------
cd /d "%~dp0"
%PYTHON_CMD% manage.py makemigrations
%PYTHON_CMD% manage.py migrate
echo.

echo ----------------------------------------
echo [4] 检查结果
echo ----------------------------------------
if exist "db.sqlite3" (
    echo [成功] 数据库文件已创建: db.sqlite3
) else (
    echo [失败] 数据库文件未创建
)
echo.

echo ========================================
echo 初始化完成!
echo ========================================
echo.
echo 启动服务器命令:
echo %PYTHON_CMD% manage.py runserver 8000
echo.
pause
